#include <REGX52.H>
#include "Delay.h"

sbit DHT11_DataIO = P2^7;
unsigned char k;

unsigned char DHT11_Data[5]; // ???????8?????8?????8?????8?????

/**
 * @brief DHT11???
 */
void DHT11_Init(void)
{
    DHT11_DataIO = 1; // ??????
}

/**
 * @brief ?DHT11??????
 * @retval ?????
 */
unsigned char DHT11_ReadByte(void)
{
    unsigned char i,  byte = 0;
    
    for(i = 0; i < 8; i++)
    {
        // ???????(?????)
        while(!DHT11_DataIO);
        
        // ??40us,?????????
        // ????????30us,????1,???0
        k=15;
        while(--k); // ??40us
        
        if(DHT11_DataIO)
        {
            // ????????,????1
            byte |= (0x80 >> i);
            // ???????
            while(DHT11_DataIO);
        }
        else
        {
            // ????????,????0
            // ???????,??byte???0
        }
    }
    
    return byte;
}


bit DHT11_ReadData(void)
{
    unsigned char i;
    unsigned char checksum;
    

    DHT11_DataIO = 0;
    Delay(18);
    DHT11_DataIO = 1;
    

    k=15;
    while(--k);
    
    while(DHT11_DataIO); 
    while(!DHT11_DataIO); 
    while(DHT11_DataIO);
    

    for(i = 0; i < 5; i++)
    {
        DHT11_Data[i] = DHT11_ReadByte();
    }
    

    checksum = DHT11_Data[0] + DHT11_Data[1] + DHT11_Data[2] + DHT11_Data[3];
    

    if(checksum == DHT11_Data[4])
    {
        return 1; 
    }
    else
    {
        return 0; 
    }
}

unsigned char DHT11_GetTemperature(void)
{
    return DHT11_Data[2]; 
}


unsigned char DHT11_GetHumidity(void)
{
    return DHT11_Data[0]; 
}

unsigned char DHT11_GetTemperatureDecimal(void)
{
    return DHT11_Data[3]; 
}


unsigned char DHT11_GetHumidityDecimal(void)
{
    return DHT11_Data[1]; 
}